package org.wmq.travelagency02.interceptor;

import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.wmq.travelagency02.model.Entity.CacheUserInfo;
import org.wmq.travelagency02.model.Entity.Result;
import org.wmq.travelagency02.common.UserContext;
import org.wmq.travelagency02.helper.JwtLoginHelper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            response.getWriter().write(JSON.toJSONString(Result.error("用户登陆异常，请重新登录")));
            return false;
        }
        String cacheJsonString = this.stringRedisTemplate.opsForValue().get(token);// 添加 JWT 负载
        if (cacheJsonString == null ||  cacheJsonString.isEmpty()){
            response.getWriter().write(JSON.toJSONString(Result.error("用户登陆异常，请重新登录")));
            return false;
        }
        UserContext.setUser(JSON.parseObject(cacheJsonString, CacheUserInfo.class));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}

